package com.sj;

import com.sj.config.OAuth2Properties;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;

@AllArgsConstructor
@RestController
@SpringBootApplication
public class BrowserClientApplication {

	public static void main(String[] args) {
		SpringApplication.run(BrowserClientApplication.class, args);
	}

	OAuth2RestTemplate oAuth2RestTemplate;

	@GetMapping("/")
	public String welcome() {
		return "welcome";
	}

	@RequestMapping("/user")
	public Principal user(Principal user) {
		return user;
	}

	@GetMapping("/test")
	public Object t(){
		return oAuth2RestTemplate.getForObject("http://localhost:8080/account/account?name=admin",String.class);
	}


	@AllArgsConstructor
	@Component
	@EnableOAuth2Sso // 实现基于OAuth2的单点登录，建议跟踪进代码阅读以下该注解的注释，很有用
	public static class SecurityConfiguration extends WebSecurityConfigurerAdapter {

		private OAuth2Properties oAuth2Properties;

		@Override
		public void configure(HttpSecurity http) throws Exception {
			http.
					antMatcher("/**")
					// 所有请求都得经过认证和授权
					.authorizeRequests().anyRequest().authenticated()
					.and()
					// 这里之所以要禁用csrf，是为了方便。
					// 否则，退出链接必须要发送一个post请求，请求还得带csrf token
					// 那样我还得写一个界面，发送post请求
					.csrf().disable()
					// 退出的URL是/logout
					.logout().logoutUrl("/logout")
					// 退出成功后，跳转到/路径。
					.logoutSuccessUrl(oAuth2Properties.getLogoutSuccessUrl()).permitAll();
		}
	}
}
